package cn.tedu.store.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.tedu.store.bean.Address;
import cn.tedu.store.mapper.AddressMapper;
import cn.tedu.store.mapper.DictMapper;
@Service
public class AddressService implements IAddressService{
	@Resource
	private AddressMapper addressMapper;
	@Resource
	private DictMapper dictMapper;
	
	public void addAddress(Address address) {
		String pName=dictMapper.getProvinceByCode(address.getRecvProvince());
		String cName=dictMapper.getCityByCode(address.getRecvCity());
		String aName=dictMapper.getAreaByCode(address.getRecvArea());
		address.setRecvDistrict(pName+cName+aName);
		List<Address> listA=addressMapper.getAddressByUid(address.getUid());
		int n=listA.size()>0?0:1;
		address.setIsDefault(n);
		addressMapper.insert(address);
	}
	/**
	 * 通过uid查询该用户的收件地址,并返回集合
	 */
	public List<Address> getAllAddressByUid(Integer uid) {
		// TODO Auto-generated method stub
		return addressMapper.getAddressByUid(uid);
	}
	/**
	 * 把所有的isDefault设置为0，再把相应id的isdefault设置为1
	 */
	public void setDefault(Integer uid, Integer id) {
		addressMapper.setCancel(uid);
		addressMapper.setDefault(id);
		
	}
	/**
	 * 通过id查询Address信息，并返回该Address信息
	 */
	public Address getAddressById(Integer id) {
		
		return addressMapper.getAddressById(id);
	}
	/**
	 * 修改地址
	 */
	public void updateAddress(Address address) {
		String pName=dictMapper.getProvinceByCode(address.getRecvProvince());
		String cName=dictMapper.getCityByCode(address.getRecvCity());
		String aName=dictMapper.getAreaByCode(address.getRecvArea());
		
		address.setRecvDistrict(pName+cName+aName);
		addressMapper.update(address);
		System.out.println("Service updateAddress");
	}
	/**
	 * 删除指定id的地址
	 */
	public void deleteAddress(Integer id, Integer uid) {
		Address address=addressMapper.getAddressById(id);
		Integer i=addressMapper.deleteAddress(id);
		if(i==1){
			if(address.getIsDefault()==1){
				List<Address> list=addressMapper.getAddressByUid(uid);
				if(list.size()>0){
					Address addr=list.get(0);
					addressMapper.setDefault(addr.getId());
					System.out.println("设置默认");
				}else{
					System.out.println("删除异常，有可能只有一条地址，所以不能设置默认地址");
				}
			}
		}
	}
	
}
